package com.ctsi.organise.app.rest;

import com.ctsi.commons.util.UtilDateTime;
import com.ctsi.commons.util.UtilMisc;
import com.ctsi.commons.util.UtilValidate;
import com.ctsi.commons.util.request.UtilHttp;
import com.ctsi.commons.util.response.Page;
import com.ctsi.framework.common.response.UnifiedResponse;
import com.ctsi.framework.mybatis.support.VoTemplate;
import com.ctsi.framework.organise.security.UserInfo;
import com.ctsi.framework.security.util.SecurityUtil;
import com.ctsi.organise.entity.PersonGW;
import com.ctsi.organise.entity.PersonRZ;
import com.ctsi.organise.query.PersonGwQuery;
import com.ctsi.organise.service.PersonGwService;
import com.ctsi.organise.service.PersonRzService;
import com.ctsi.organise.vo.PersonGwVO;
import com.ctsi.organise.vo.PersonRzVO;
import com.ctsi.product.entity.Upload;
import com.ctsi.product.service.UploadService;
import com.ctsi.product.vo.FileResourceVO;
import com.ctsi.system.service.api.DictionaryServiceProxy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @auth:wgf
 * @description :
 * @Date: 2019/3/15
 */
@RestController
public class PersonGWORRZController {
    @Autowired
    private PersonGwService personGwService;
    @Autowired
    private PersonRzService personRzService;
    @Autowired
    private VoTemplate voTemplate;
    @Autowired
    private DictionaryServiceProxy dictionaryServiceProxy;
    @Autowired
    private UploadService uploadService;
    @Value("${file-store.host}")
    private String fileServerHost;
    /**
     * 岗位列表
     */
    @PostMapping(value = "/person/queryListPersonGW",consumes = "application/json",produces = "application/json;charset=UTF-8")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Page<PersonGwVO>> queryListPersonGW(@RequestBody PersonGwQuery ppp){
        Page<PersonGW> result = personGwService.queryListPersonGW(UtilHttp.filterBlank(UtilMisc.toMap(ppp)),ppp.getStart(),ppp.getPageSize());
        List<PersonGwVO> personGwVOList=result.getResult().stream().map(lib ->{
            String gw_typename = dictionaryServiceProxy.getDictValue("gw_type", lib.getGwmc());
            PersonGwVO personGwVO=voTemplate.defaultExcute(new PersonGwVO(),lib);
            personGwVO.setGwmcname(gw_typename);
            personGwVO.setDgtimeStr(UtilDateTime.longToString(lib.getDgtime(),UtilDateTime.defaultDatePattern));
            return personGwVO;
        }).collect(Collectors.toList());
        return UnifiedResponse.ok(new Page<>(ppp.getStart(),result.getTotalCount(),result.getPageSize(),personGwVOList));
    }
    /**
     * 认证列表
     */
    @PostMapping(value = "/person/queryListPersonRZ",consumes = "application/json",produces = "application/json;charset=UTF-8")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Page<PersonRzVO>> queryListPersonRZ(@RequestBody PersonGwQuery ppp){
        Page<PersonRZ> personRZPage = personRzService.queryListPersonRZ(UtilHttp.filterBlank(UtilMisc.toMap(ppp)), ppp.getStart(), ppp.getPageSize());
        List<PersonRzVO> personGwVOList=personRZPage.getResult().stream().map(lib ->{
            PersonRzVO personRzVO=voTemplate.defaultExcute(new PersonRzVO(),lib);
            String rzjb_typename = dictionaryServiceProxy.getDictValue("rzjb_type", lib.getRzjb());
            String rz_typename = dictionaryServiceProxy.getDictValue("rz_type", lib.getRzlx());
            personRzVO.setRzjbname(rzjb_typename);
            personRzVO.setRzlxname(rz_typename);
            Map<String,Object> param = new HashMap<>();
            param.put("personrzid",lib.getId());
            List<Upload> uploads = uploadService.find(param);
            List<FileResourceVO> fvos = uploads.stream().map(upload -> {
                FileResourceVO fvo=new FileResourceVO();
                String webPath = upload.getSavepath().replace("\\", "/");
                String url = (fileServerHost.endsWith("/") ? fileServerHost : fileServerHost.concat("/")) +
                        (webPath.startsWith("/") ? "files/org/api/file" : "files/org/api/file/") + webPath;
                fvo.setUrl(url);
                return fvo;
            }).collect(Collectors.toList());
            Optional<FileResourceVO> optionalFileResourceVO = fvos.stream().findFirst();
            if (optionalFileResourceVO.isPresent()) {
                personRzVO.setImgurl(optionalFileResourceVO.get().getUrl());
            }
            return personRzVO;
        }).collect(Collectors.toList());
        return UnifiedResponse.ok(new Page<>(ppp.getStart(),personRZPage.getTotalCount(),personRZPage.getPageSize(),personGwVOList));
    }
    /**
     * 岗位添加和修改
     */
    @PostMapping(value = "/person/addOrEditGW",consumes = "application/json",produces = "application/json;charset=UTF-8")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Integer> addOrEditGW(@RequestBody PersonGW personGW){
        if(UtilValidate.isEmpty(personGW.getId())){
            String gwmc_name = dictionaryServiceProxy.getDictValue("gw_type", personGW.getGwmc());
            personGW.setGwmc_name(gwmc_name);
            int i = personGwService.insertPersonGw(personGW);
            return UnifiedResponse.ok(i);
        }else {
            int i = personGwService.updatePersonGwByPKSelective(personGW);
            return UnifiedResponse.ok(i);
        }
    }
    /**
     * 认证添加及修改
     */
    @PostMapping(value = "/person/addOrEditRZ",consumes = "application/json",produces = "application/json;charset=UTF-8")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Integer> addOrEditRZ(@RequestBody PersonRZ personRZ){
        UserInfo user = SecurityUtil.getUser();
        if(UtilValidate.isEmpty(personRZ.getId())){
            String id= String.valueOf(UUID.randomUUID());
            personRZ.setId(id);
            if(UtilValidate.isNotEmpty(personRZ.getImgurl())){
                Upload upload=new Upload();
                upload.setUserid(user.getUserId());
                upload.setCreatetime(System.currentTimeMillis());
                upload.setFilename(personRZ.getImgname());
                upload.setIsdefault("0");
                upload.setPersonrzid(personRZ.getId());
                upload.setSavepath(personRZ.getImgurl());
                uploadService.insertUpload(upload);
            }
            int i = personRzService.insertPersonRz(personRZ);
            return UnifiedResponse.ok(i);
        }else {
            String imgurl="";
            String name="";
            String name1="";
            if(UtilValidate.isNotEmpty(personRZ.getImgurl())){
                String url=personRZ.getImgurl();
                String temp[] = url.replaceAll("\\\\","/").split("/");
                if (temp.length > 1) {
                    name = temp[temp.length - 1];
                    name1= temp[temp.length - 2];
                }
                if(url.startsWith("http")==true){
                    imgurl=name1+ File.separator+name;
                }else {
                    imgurl=url;
                }
                Upload upload=new Upload();
                upload.setUserid(user.getUserId());
                upload.setCreatetime(System.currentTimeMillis());
                upload.setFilename(personRZ.getImgname());
                upload.setIsdefault("0");
                upload.setPersonrzid(personRZ.getId());
                upload.setSavepath(imgurl);
                uploadService.insertUpload(upload);
            }
            int i = personRzService.updatePersonRZByPKSelective(personRZ);
            return UnifiedResponse.ok(i);
        }
    }
    /**
     * 根据ID查询岗位详情
     */
    @PostMapping(value = "/person/findPersonGWById",produces = "application/json;charset=UTF-8" )
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<PersonGwVO> findPersonGWById(@RequestParam("id") String id){
        if (UtilValidate.isEmpty(id)){
            return UnifiedResponse.ok(null);
        }
        PersonGW result = personGwService.findPersonGWById(id);
        PersonGwVO personGwVO=voTemplate.defaultExcute(new PersonGwVO(),result);
        if(UtilValidate.isNotEmpty(String.valueOf(result.getDgtime()))){
            personGwVO.setDgtimeStr(UtilDateTime.longToString(result.getDgtime()));
        }
        return UnifiedResponse.ok(personGwVO);
    }
    /**
     * 根据ID查询认证详情
     */
    @PostMapping(value = "/person/findPersonRZById",produces = "application/json;charset=UTF-8" )
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<PersonRZ> findPersonRZById(@RequestParam("id") String id){
        if (UtilValidate.isEmpty(id)){
            return UnifiedResponse.ok(null);
        }
        PersonRZ result = personRzService.findPersonRZById(id);
        Map<String,Object> param = new HashMap<>();
        param.put("personrzid",id);
        List<Upload> uploads = uploadService.find(param);
        List<FileResourceVO> fvos = uploads.stream().map(upload -> {
            FileResourceVO fvo=new FileResourceVO();
            String webPath = upload.getSavepath().replace("\\", "/");
            String url = (fileServerHost.endsWith("/") ? fileServerHost : fileServerHost.concat("/")) +
                    (webPath.startsWith("/") ? "files/org/api/file" : "files/org/api/file/") + webPath;
            fvo.setUrl(url);
            return fvo;
        }).collect(Collectors.toList());
        Optional<FileResourceVO> optionalFileResourceVO = fvos.stream().findFirst();
        if (optionalFileResourceVO.isPresent()) {
            result.setImgurl(optionalFileResourceVO.get().getUrl());
        }
        return UnifiedResponse.ok(result);
    }
    /**
     * 删除 岗位
     */
    @PostMapping(value = "/person/deletePersonGw",produces = "application/json;charset=UTF-8")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Integer> deletePersonGw(@RequestParam("id") String id){
            if (UtilValidate.isNotEmpty(id)){
                PersonGW personGW=new PersonGW();
                personGW.setIs_delete(1);
                personGW.setId(id);
                int i = personGwService.updatePersonGwByPKSelective(personGW);
                return UnifiedResponse.ok(i);
            }else {
                return UnifiedResponse.ok(0);
            }
         }
    /**
     * 删除认证
     */
    @PostMapping(value = "/person/deletePersonRz",produces = "application/json;charset=UTF-8")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Integer> deletePersonRz(@RequestParam("id") String id){
        if (UtilValidate.isNotEmpty(id)){
            PersonRZ personRZ=new PersonRZ();
            personRZ.setIs_delete(1);
            personRZ.setId(id);
            int i = personRzService.updatePersonRZByPKSelective(personRZ);
            return UnifiedResponse.ok(i);
        }else {
            return UnifiedResponse.ok(0);
        }
    }
}
